<template>
  <el-dialog
    :append-to-body="true"
    :visible.sync="visible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @closed="closeHandler"
    width="50%" top="25vh">
    <el-input id="StreamProgressLogs" ref="logs"
              type="textarea"
              :rows="15" readonly
              v-model="content">
    </el-input>
    <span slot="title" class="dialog-footer">
      <i class="el-icon-loading"></i>正在执行任务，不要关闭窗口，请在任务完成后点击确定...
    </span>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" type="primary" @click="visible = false">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import pubsub from 'pubsub-js'
import {myIdKey, bytesToSize} from "@/utils";

export default {
  name: "StreamProgress",
  data() {
    return {
      id: '',
      visible: false,
      content: ''
    }
  },
  methods: {
    analysis(data) {
      let content = ''
      data.split(new RegExp('\n')).forEach((item) => {
        item = item.trim()
        let isJson = item.startsWith('{') && item.endsWith('}')
        if (isJson) {
          let res = JSON.parse(item)
          if (res.status && res.id) {
            let downloadingText = '';
            if (['Downloading', 'Extracting'].indexOf(res.status) > -1) {
              let current = bytesToSize(res.progressDetail.current);
              let total = bytesToSize(res.progressDetail.total);
              downloadingText = ` ${current.value}${current.unit}/${total.value}${total.unit} ${(res.progressDetail.current / res.progressDetail.total * 100).toFixed(2)}%`
            }
            content += res.status + ' ' + res.id
              + downloadingText
              + '\n';
          } else if (res.status) {
            content += res.status + '\n'
          }
        } else {
          content += item + '\n'
        }
      })
      return content
    },
    show(subId) {
      this.id = subId
      this.visible = true
      this.content = 'loading....'
      pubsub.subscribe(this.id + 'progress', (msgName, data) => {
        this.content = this.analysis(data)

        this.$nextTick(() => {
          let textarea = document.getElementById('StreamProgressLogs');
          if (textarea) {
            textarea.scrollTop = textarea.scrollHeight;
          }
        })
      })
    },
    closeHandler() {
      this.$emit('close')
    }
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.id + 'progress');
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__body {
  padding: 10px;
}
</style>
